package com.tansun.rule.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.drools.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.tansun.ruledata.service.RuleDataBusinessService;

import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;

@Controller
@RequestMapping(value = "/")
public class ProjectController {
	
	@Autowired
	private RuleDataBusinessService ruleDataBusinessService;
	
    /**
     * Counter类型，只能递增，不能自定义值
     * name: 改类型的名称
     * labelNames： requestTotal相当于redis的hashmap的key，labelNames相当于hashmap的key的label
     * help：备注说明
     */
    private static final Counter requestTotal = Counter.build().name("ruleexceptioncounter").labelNames("uri").help
            ("total request couter of api").register();
    /**
     * Gauge： 可以自定义值，比如内存的变化。
     */
    private static final Gauge myKEy = Gauge.build().name("mem").labelNames("tran_count").help
            ("show mem info").register();
	
	
	@RequestMapping(value = "/ruleservice/execute")
	public @ResponseBody String execute(HttpServletRequest request, HttpServletResponse response,ModelMap map) throws Exception {
		String projectCode = request.getParameter("projectCode");
		String enterPoint = request.getParameter("enterPoint");
		String businessInput = request.getParameter("businessInput");
		String type = request.getParameter("type");
		String result = "";
		try {
			if (StringUtils.isEmpty(type)) {
				type = "json";
			}
			result = ruleDataBusinessService.ruleEngineService(projectCode, enterPoint, type, businessInput);
			Map<String,Object> resultMap = JSON.parseObject(result,Map.class);
			Map<String,Object> systemMap = (Map<String, Object>) resultMap.get("System");
			if("0".equals(systemMap.get("isSuccess").toString())) {
				requestTotal.labels("/ruleservice/execute").inc();
			}
		}catch (Exception e) {
			// TODO: handle exception
			requestTotal.labels("/ruleservice/execute_error").inc();
		}

		return result;
	}
	
	
	@RequestMapping("/feigntest")
	public @ResponseBody String feigntest() {
		return "feigntest";
	}
	@RequestMapping(value = "/hello/{name}")
	public @ResponseBody String index(@PathVariable("name") String name) {
		return "hello " + name + "，this is from producer!";
	}
}